import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xmshop/app/models/plist_model.dart';
import 'package:xmshop/app/services/httpsClient.dart';

class ProductListController extends GetxController {
  //TODO: Implement ProductListController
  ScrollController scrollController = ScrollController();
  RxList<PlistItemModel> plistItem = <PlistItemModel>[].obs;
  RxInt page = 1.obs;
  int pageSize = 8;
  bool flag = true;
  RxBool hasData = true.obs;
  HttpsClient httpsClient = HttpsClient();
  GlobalKey<ScaffoldState> globalKey = GlobalKey<ScaffoldState>();
  List subHeaderList = [
    {"id": 1, "title": "综合", "fileds": "all", "sort": -1},
    {"id": 2, "title": "销量", "fileds": "salecount", "sort": -1},
    {"id": 3, "title": "价格", "fileds": "price", "sort": -1},
    {"id": 4, "title": "筛选"},
  ];
  RxInt selectHeaderId = 1.obs;
  RxString sort = "".obs;
  //解决排序箭头无法更新
  RxInt subHeaderListSort = 1.obs;
  //获取传值
  String? keywords = Get.arguments['keywords'];
  String? cid = Get.arguments['cid'];
  String apiUri = "";
  @override
  void onInit() {
    super.onInit();
    getPlistData();
    initScrollController();
  }

  //监听滚动条事件
  initScrollController() {
    scrollController.addListener(() {
      //scrollController.position.pixels 滚动条下拉的高度
      //scrollController.position.maxScrollExtent 页面的高度
      if (scrollController.position.pixels >
          scrollController.position.maxScrollExtent - 20) {
        getPlistData();
      }
    });
  }

  getPlistData() async {
    if (flag && hasData.value) {
      flag = false;
      if (cid != null) {
        apiUri =
            "api/plist?cid=$cid&page=${page.value}&pageSize=$pageSize&sort=${sort.value}";
      } else {
        apiUri =
            "api/plist?search=$keywords&page=${page.value}&pageSize=$pageSize&sort=${sort.value}";
      }
      var response = await httpsClient.get(apiUri);
      print(
        "api/plist?cid=${Get.arguments["cid"]}&page=${page.value}&pageSize=$pageSize&sort=${sort.value}",
      );
      if (response != null) {
        var plist = PlistModel.fromJson(response.data);
        //plistItem.value = plist.result!;
        plistItem.addAll(plist.result!); //拼接数据
        page.value++;
        flag = true;
        if (plist.result!.length < pageSize) {
          hasData.value = false;
        }
      }
    }
  }

  changeSelect(index) {
    if (index == 4) {
      globalKey.currentState?.openEndDrawer();
      selectHeaderId.value = index;
    } else {
      selectHeaderId.value = index;
      sort.value =
          "${subHeaderList[index - 1]["fileds"]}_${subHeaderList[index - 1]["sort"]}";
      //切换排序
      subHeaderList[index - 1]["sort"] = subHeaderList[index - 1]["sort"] * -1;
      subHeaderListSort.value = subHeaderList[index - 1]["sort"];
      //重置请求数据
      page.value = 1;
      plistItem.value = [];
      hasData.value = true;
      scrollController.jumpTo(0); //回到顶部
      //重新请求接口数据
      getPlistData();
    }
  }
}
